package com.liang.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.liang.pojo.User;
import com.liang.service.UserService;

public class UserRealm extends AuthorizingRealm{
	@Autowired
	UserService userService;
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("授权===================");
		String username=principals.getPrimaryPrincipal().toString();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		User user = userService.selectUserByUsername(username);
		Set<String> set = new HashSet<String>();
		Set<String> set2 = new HashSet<String>();
		set.add(user.getUsername());
		set2.add(user.getPermissions());
		info.setRoles(set);
		info.setStringPermissions(set2);
		System.out.println(user.getUsername()+"+"+user.getPermissions());
		return info;
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("认证====================");
		String username=token.getPrincipal().toString();
		User user = userService.selectUserByUsername(username);
		if(user==null) {
			return null;
		}else {
			System.out.println(user.getPassword());
			String realName=getName();
			 //盐值
	        ByteSource salt = ByteSource.Util.bytes(user.getUsername());
	        //封装用户信息，构建AuthenticationInfo对象并返回
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
	                salt,realName);
	        return authcInfo;
		}
		
	}

}
